package de.dopichaj.labrador.search.own;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.SortedSet;
import java.util.TreeSet;

import de.dopichaj.labrador.index.Index;
import de.dopichaj.labrador.index.backend.TermFrequency;
import de.dopichaj.labrador.search.hit.ChainedHit;
import de.dopichaj.labrador.search.hit.Hit;
import de.dopichaj.labrador.search.hit.PosComparator;


/**
 * Assumes {@link Hit}s are really {@link ChainedHit}s and that the similarity
 * function is called bottom-up. 
 */
public final class PatternSimilarityFactory implements SimilarityFactory {

    private final SimilarityFactory similarityFactory;
    private final double boostFactor;
    
    public PatternSimilarityFactory(final SimilarityFactory similarityFactory,
        final double boostFactor) {
        
        this.similarityFactory = similarityFactory;
        this.boostFactor = boostFactor;
    }
    
    public PatternSimilarityFactory(final Index index) {
        this(new GPXSimilarityFactory(index),
            index.getConfiguration().getDouble("patternBoost", 2.0));
    }
    
    public String getDescription() {
        return "Pattern similarity (boost=" + boostFactor + ")";
    }

    private final class PatternSimilarity implements Similarity {

        private final Similarity similarity;
        private final Map<Hit, SortedSet<Hit>> childMap =
            new HashMap<Hit, SortedSet<Hit>>();
        private final List<Hit> hitsInCurrentDocument = new ArrayList<Hit>();
        
        public PatternSimilarity(final Similarity similarity) {
            this.similarity = similarity;
        }
        
        public double similarity(Hit inputHit, List<TermFrequency> frequencyList) {

            final ChainedHit hit = (ChainedHit)inputHit;
            
            // get children and remove them
            final SortedSet<Hit> children = childMap.get(hit);
            childMap.remove(hit);
            
            // get base score
            double score = frequencyList != null
                ? similarity.similarity(inputHit, frequencyList) : 0;

            score = updateScore(hit, children, score);

            // add to parent's children
            if (!childMap.containsKey(hit.getParent())) {
                childMap.put(hit.getParent(), new TreeSet<Hit>(PosComparator.INSTANCE));
            }
            childMap.get(hit.getParent()).add(hit);
            
            // return the score
            return score;
        }

        private double updateScore(final ChainedHit hit,
            final SortedSet<Hit> children, double score) {

            // calculate score of branch elements
            if (children != null) {

                double sum = 0;
                for (final Hit child : children) {
                    sum += child.getScore();
                }

                final double d = children.size() == 1 ? 0.1 : 0.1;
                sum *= d;
                
                score += sum;
            }

            // if this is the root element
            if (hit.getDepth() == 0) {
                
                // add root's score to all elements' scores
                hit.setScore((float)score);
                for (final Hit h : hitsInCurrentDocument) {
                    h.setScore(h.getScore() + (float)score);
                }
                
                // clear document's hits
                hitsInCurrentDocument.clear();
                
                score = 2 * score;
            } else {
                hitsInCurrentDocument.add(hit);
            }
            return score;
        }
    }
    
    public Similarity getSimilarity(OwnQuery query) {
        
        return new PatternSimilarity(similarityFactory.getSimilarity(query));
    }

}
/*
Copyright (c) 2005-2007 Philipp Dopichaj

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/